<template>
  <div class="qq-sty">
    <a-layout style="height: 100%">
      <a-layout-header
        style="background-color: white; border-bottom: 1px solid grey"
      >
        <a-avatar
          src="https://cdn.acwing.com/media/file_system/file/application/icon/2220490481555590627-128_UQONKkk.png"
        />
        &nbsp;聊天
      </a-layout-header>
      <a-layout>
        <a-layout-sider style="background: #f0f2f5">
          <a-menu
            v-model:selectedKeys="s_user"
            v-model:openKeys="s_menu"
            mode="inline"
            :style="{ height: '100%', borderRight: 0 }"
          >
            <!-- <a-sub-menu key="sub1">
              <template #title>
                <span>
                  <user-outlined />
                  公共频道
                </span>
              </template>
              <a-menu-item
                v-for="user of userlist"
                :key="user"
                @click="select_user(user.id)"
              >
                <a-avatar :src="user.photo"></a-avatar>
                {{ user.username }}
              </a-menu-item>
            </a-sub-menu> -->
            <a-sub-menu key="sub2">
              <template #title>
                <span>
                  <laptop-outlined />
                  在线好友
                </span>
              </template>
              <a-menu-item
                v-for="user of on_friend"
                :key="user"
                @click="select_user(user.id)"
              >
                <a-avatar :src="user.photo"></a-avatar>
                {{ user.username }}
              </a-menu-item>
            </a-sub-menu>
            <a-sub-menu key="sub3">
              <template #title>
                <span>
                  <notification-outlined />
                  离线好友
                </span>
              </template>
              <a-menu-item
                v-for="user of off_friend"
                :key="user"
                @click="select_user(user.id)"
              >
                <a-avatar :src="user.photo"></a-avatar>
                {{ user.username }}
              </a-menu-item>
            </a-sub-menu>
          </a-menu>
        </a-layout-sider>
        <a-layout style="padding: 0 24px 24px">
          <a-breadcrumb style="margin: 10px 0" v-if="!user"> </a-breadcrumb>
          <a-breadcrumb style="margin: 10px 0" v-if="user">
            <a-breadcrumb-item>
              <a-avatar :src="user.photo"></a-avatar>
              {{ user.username }}
            </a-breadcrumb-item>
          </a-breadcrumb>
          <a-layout-content
            id="scrolldIV"
            :style="{
              background: '#fff',
              padding: '12px',
              margin: 0,
              minHeight: '300px',
              maxHeight: '60%',
              overflow: 'auto',
            }"
          >
            <a-comment v-for="message of messageList" :key="message.id">
              <template #author>
                <a v-if="message.MId === user.id">{{ user.username }}</a>
                <a v-else>{{ my.username }}</a>
              </template>
              <template #avatar>
                <a-avatar
                  v-if="message.MId === user.id"
                  :src="user.photo"
                  alt="头像"
                />
                <a-avatar v-else :src="my.avatar" alt="头像" />
              </template>
              <template #content>
                <p v-html="message.message"></p>
              </template>
              <template #datetime>
                <a-tooltip>
                  <span>{{ message.createTime }}</span>
                </a-tooltip>
              </template>
            </a-comment>
            <br />
          </a-layout-content>
          <a-layout-content
            :style="{
              background: '#fff',
              padding: '12px',
              margin: 0,
              maxHeight: '40%',
            }"
          >
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 18vh; overflow-y: hidden"
                v-model="content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
              <a-button
                style="float: right; margin-top: 10px"
                @click="sendMessage()"
                type="primary"
              >
                提交
              </a-button>
            </div>
          </a-layout-content>
        </a-layout>
      </a-layout>
    </a-layout>
  </div>
</template>

<script>
import { useStore } from "vuex";
import {
  computed,
  onBeforeUnmount,
  onMounted,
  onUnmounted,
  ref,
  shallowRef,
} from "@vue/runtime-core";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { message } from "ant-design-vue";
export default {
  name: "MessageView",
  components: { Editor, Toolbar },
  setup() {
    const store = useStore();
    const access = store.state.user.info.access;
    const my = store.state.user.info;

    const socketQQURL = store.state.web.webAddress + `/websocket/qq/${access}`;
    let socket = null;

    const userlist = ref([]);

    const s_user = ref([]);
    const s_menu = ref([]);
    const messageList = ref([]);
    const off_friend = ref([]);
    const on_friend = ref([]);

    let user = computed(() => {
      if (s_user.value) return s_user.value[0];
      return "";
    });

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    onMounted(() => {
      socket = new WebSocket(socketQQURL);

      socket.onopen = () => {
        store.commit("updateSocket", socket);
      };

      socket.onmessage = (msg) => {
        const temp = JSON.parse(msg.data);
        const data = temp.data;
        const event = temp.event;
        if (event === "userlist") {
          userlist.value = data;
        } else if (event === "get-msglist") {
          messageList.value = data;
          sty();
        } else if (event === "send-msg") {
          messageList.value.push(data);
          sty();
        } else if (event === "online-friend") {
          on_friend.value = data;
        } else if (event === "offline-friend") {
          off_friend.value = data;
        } else if (event === "close") {
          let temp;
          for (let i = 0; i < userlist.value.length; i++) {
            if (userlist.value[i].id === data) {
              temp = userlist.value[i];
            }
          }

          on_friend.value = on_friend.value.filter((i) => {
            i.id !== data;
          });

          off_friend.value = off_friend.value.filter((i) => {
            i.id !== data;
          });

          off_friend.value.push(temp);
        } else if (event === "get-online-friend") {
          on_friend.value = on_friend.value.filter((i) => {
            i.id !== data.id;
          });

          off_friend.value = off_friend.value.filter((i) => {
            i.id !== data.id;
          });
          on_friend.value.push(data);
        }
      };

      socket.onclose = () => {
        console.log("关闭聊天");
      };
    });

    onUnmounted(() => {
      socket.close();
      store.commit("updateStatus", "matching");
    });

    const sty = () => {
      let div = document.getElementById("scrolldIV");
      div.scrollTop = div.scrollHeight;
    };

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();

    const toolbarConfig = {};

    const content = ref();

    toolbarConfig.excludeKeys = [
      "group-video",
      "headerSelect",
      "blockquote",
      "underline",
      "italic",
      "group-more-style",
      "fontSize",
      "fullScreen",
      "undo",
      "video",
      "insertTable",
      "splitLine",
      "redo",
      "bulletedList",
      "numberedList",
      "todo",
      "quote",
      "divider",
      "group-indent",
      "group-justify",
    ];

    const editorConfig = {
      placeholder: "请输入内容...",
      MENU_CONF: {
        // 配置上传图片
        uploadImage: {
          fieldName: "file",
          server: store.state.web.serverAddress + "/codes/oss/weditor/fileoss",
          headers: {
            Authorization: "token:" + access, //指定消息格式
          },
          allowedFileTypes: ["image/*"],
        },
      },
    };

    const sendMessage = () => {
      if (!content.value || s_user.value.length === 0) {
        if (s_user.value.length === 0) {
          message.warn("请选择要发生消息的对象！");
        } else if (!content.value) {
          message.warn("发送内容不能为空！");
        }
        return false;
      }
      socket.send(
        JSON.stringify({
          event: "send-msg",
          data: {
            content: content.value,
            fId: s_user.value[0].id,
          },
        })
      );
      content.value = "";
    };

    const select_user = (id) => {
      socket.send(
        JSON.stringify({
          event: "get-msg",
          data: {
            fId: id,
          },
        })
      );
    };

    return {
      my,
      userlist,
      s_user,
      s_menu,
      user,
      content,
      messageList,
      off_friend,
      on_friend,
      sendMessage,
      select_user,

      editorRef,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      sty,
    };
  },
};
</script>

<style scoped>
div.qq-sty {
  background-color: lightblue;
  margin-top: 20px;
  margin-left: 15vw;
  width: 70vw;
  height: 95vh;
}
div.msg-sty {
  width: 100%;
  height: 100%;
}
</style>